<template>
    <!-- 搜索部分 -->
    <div class="search-box">
        <el-row>
            <el-col :span="9">
                <el-button type="primary" @click="handleAdd"><el-icon><Plus /></el-icon>&nbsp;添加记录</el-button>
            </el-col>
            <el-col :span="5">
                <el-input v-model.trim="searchInfo.user" style="width: 240px" placeholder="请输入咨询用户姓名" />
            </el-col>
            <el-col :span="3">
                <el-button type="primary" @click="search">查询</el-button>
                <el-button type="primary" @click="reset">重置</el-button>
            </el-col>
        </el-row>
    </div>
    <!-- 表格部分 -->
    <div class="table-box">
        <el-table :data="currentTableData" style="width: 100%" height="450px" :header-cell-style="{ 'background-color': '#f5f7fa' }">
            <el-table-column prop="user" label="咨询用户" width="120" />
            <el-table-column prop="consultationTime" label="咨询时段" width="180" />
            <el-table-column prop="counselor" label="咨询师" width="120" />
            <el-table-column prop="issue" label="咨询问题" width="120" />
            <el-table-column prop="complaint" label="主诉" min-width="180" />
            <el-table-column prop="analysis" label="咨询师分析" min-width="180" />
            <el-table-column prop="notes" label="备注" min-width="180" />
            <el-table-column fixed="right" label="操作" width="150">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!-- 添加/编辑记录对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="40%">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
            <el-form-item label="咨询用户" prop="user">
                 <el-input v-model="form.user" placeholder="请输入咨询用户" />
            </el-form-item>
            <el-form-item label="咨询师" prop="counselor">
                <el-select v-model="form.counselor" placeholder="请选择咨询师">
                    <el-option v-for="c in counselorOptions" :key="c" :label="c" :value="c" />
                </el-select>
            </el-form-item>
            <el-form-item label="咨询日期" prop="date">
                <el-date-picker v-model="form.date" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="咨询时段" prop="timeRange">
                <el-time-picker
                    v-model="form.timeRange"
                    is-range
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                />
            </el-form-item>
            <el-form-item label="咨询问题" prop="issue">
                <el-select v-model="form.issue" placeholder="请选择咨询问题">
                    <el-option v-for="i in issueOptions" :key="i" :label="i" :value="i" />
                </el-select>
            </el-form-item>
            <el-form-item label="主诉" prop="complaint">
                <el-input v-model="form.complaint" type="textarea" />
            </el-form-item>
            <el-form-item label="咨询师分析" prop="analysis">
                <el-input v-model="form.analysis" type="textarea" />
            </el-form-item>
            <el-form-item label="备注">
                <el-input v-model="form.notes" type="textarea" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="save">保存</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 分页部分 -->
    <div class="page-box">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="currentPageSize"
            :page-sizes="[10, 20, 30, 50]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const tableData = ref([]);
const tableDataCopy = ref([]);
const currentTableData = ref([]);
const currentPage = ref(1);
const currentPageSize = ref(10);
const searchInfo = ref({ user: '' });

const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref(null);

const form = ref({
    id: null,
    user: '',
    counselor: '',
    date: '',
    timeRange: null,
    issue: '',
    complaint: '',
    analysis: '',
    notes: ''
});

const rules = {
    user: [{ required: true, message: '请输入咨询用户', trigger: 'blur' }],
    counselor: [{ required: true, message: '请选择咨询师', trigger: 'change' }],
    date: [{ required: true, message: '请选择咨询日期', trigger: 'change' }],
    timeRange: [{ required: true, message: '请选择咨询时段', trigger: 'change' }],
    issue: [{ required: true, message: '请选择咨询问题', trigger: 'change' }],
    complaint: [{ required: true, message: '请输入主诉', trigger: 'blur' }],
    analysis: [{ required: true, message: '请输入咨询师分析', trigger: 'blur' }]
};

const counselorOptions = ['咨询师1', '咨询师2', '咨询师3'];
const issueOptions = ['学业压力', '家庭关系', '人际交往', '自我认知', '情绪管理', '个人成长', '职业生涯', '亲子关系'];

const handleSizeChange = (newPageSize) => {
  currentPageSize.value = newPageSize;
  updateCurrentTableData();
}
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  updateCurrentTableData();
}

const updateCurrentTableData = () => {
    const start = (currentPage.value - 1) * currentPageSize.value
    const end = start + currentPageSize.value
    currentTableData.value = tableData.value.slice(start, end)
}

const search = () => {
    if (!searchInfo.value.user) {
        tableData.value = [...tableDataCopy.value];
    } else {
        tableData.value = tableDataCopy.value.filter(item => item.user.includes(searchInfo.value.user));
    }
    currentPage.value = 1;
    updateCurrentTableData();
}
const reset = () => {
  searchInfo.value = { user: '' }
  tableData.value = [...tableDataCopy.value];
  currentPage.value = 1;
  updateCurrentTableData();
}

const loadData = () => {
    const storedData = sessionStorage.getItem('consultationRecords');
    if (storedData) {
        tableData.value = JSON.parse(storedData);
    } else {
        // Mock data
        tableData.value = [
            {
                id: 1,
                user: '学生A',
                consultationTime: '2023-11-01 10:00 - 11:00',
                counselor: '咨询师1',
                issue: '学业压力',
                complaint: '感觉学习压力很大，难以集中注意力。',
                analysis: '初步判断为学习焦虑，建议进行放松训练。',
                notes: '首次咨询'
            }
        ];
        sessionStorage.setItem('consultationRecords', JSON.stringify(tableData.value));
    }
    tableDataCopy.value = [...tableData.value];
};

onMounted(() => {
    loadData();
    updateCurrentTableData();
});

const handleAdd = () => {
    dialogTitle.value = '添加记录';
    form.value = {
        id: null,
        user: '',
        counselor: '',
        date: '',
        timeRange: null,
        issue: '',
        complaint: '',
        analysis: '',
        notes: ''
    };
    dialogVisible.value = true;
};

const handleEdit = (row) => {
    dialogTitle.value = '编辑记录';
    const consultationTime = row.consultationTime || '';
    const timeIndex = consultationTime.indexOf(' ');
    const dateStr = timeIndex > -1 ? consultationTime.substring(0, timeIndex) : consultationTime;
    const timePart = timeIndex > -1 ? consultationTime.substring(timeIndex + 1) : '';
    const [startTimeStr, endTimeStr] = timePart ? timePart.split(' - ') : [null, null];

    let timeRange = null;
    if (dateStr && startTimeStr && endTimeStr) {
        const [year, month, day] = dateStr.split('-').map(Number);
        const [startHour, startMinute] = startTimeStr.trim().split(':').map(Number);
        const [endHour, endMinute] = endTimeStr.trim().split(':').map(Number);

        if (![year, month, day, startHour, startMinute, endHour, endMinute].some(isNaN)) {
            const startDateTime = new Date(year, month - 1, day, startHour, startMinute);
            const endDateTime = new Date(year, month - 1, day, endHour, endMinute);
            timeRange = [startDateTime, endDateTime];
        }
    }

    form.value = {
        id: row.id,
        user: row.user,
        counselor: row.counselor,
        date: dateStr,
        timeRange: timeRange,
        issue: row.issue,
        complaint: row.complaint,
        analysis: row.analysis,
        notes: row.notes
    };
    dialogVisible.value = true;
};

const save = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            let consultationTime = form.value.date;
            if (form.value.timeRange && form.value.timeRange[0] && form.value.timeRange[1]) {
                const [start, end] = form.value.timeRange;
                const startTime = `${start.getHours().toString().padStart(2, '0')}:${start.getMinutes().toString().padStart(2, '0')}`;
                const endTime = `${end.getHours().toString().padStart(2, '0')}:${end.getMinutes().toString().padStart(2, '0')}`;
                consultationTime = `${form.value.date} ${startTime} - ${endTime}`;
            }

            const record = {
                id: form.value.id || Date.now(),
                user: form.value.user,
                consultationTime: consultationTime,
                counselor: form.value.counselor,
                issue: form.value.issue,
                complaint: form.value.complaint,
                analysis: form.value.analysis,
                notes: form.value.notes
            };

            if (form.value.id) {
                // Edit
                const index = tableData.value.findIndex(item => item.id === form.value.id);
                if (index !== -1) {
                    tableData.value.splice(index, 1, record);
                }
            } else {
                // Add
                tableData.value.unshift(record);
            }
            sessionStorage.setItem('consultationRecords', JSON.stringify(tableData.value));
            tableDataCopy.value = [...tableData.value];
            updateCurrentTableData();
            ElMessage.success('保存成功');
            dialogVisible.value = false;
        } else {
            ElMessage.error('请填写所有必填项');
            return false;
        }
    });
};

const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const index = tableData.value.findIndex(item => item.id === row.id);
        if (index !== -1) {
            tableData.value.splice(index, 1);
        }
        sessionStorage.setItem('consultationRecords', JSON.stringify(tableData.value));
        tableDataCopy.value = [...tableData.value];
        updateCurrentTableData();
        ElMessage.success('删除成功');
    }).catch(() => {
        // a
    });
};

</script>

<style scoped>
.search-box {
    padding: 10px 0px 10px 10px;
}
.table-box {
    padding-left: 10px;
}
.page-box {
    display: flex;
    justify-content: center;
    padding-top: 10px;
}
</style>